# -*- coding: utf-8 -*-
import sys
import os
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel
from PySide6.QtCore import Qt
from PySide6.QtGui import QShortcut, QKeySequence

# COUNT_FILE = "counter.txt"
COUNT_FILE = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/.logs', "counter.txt"
)
# 确保目录存在
if not os.path.exists(os.path.dirname(COUNT_FILE)):
    os.makedirs(os.path.dirname(COUNT_FILE))


class CounterApp(QWidget):
    def __init__(self):
        super().__init__()
        self.count = self.load_count()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("计数器")
        self.resize(300, 200)  # 增大窗口初始面积
        self.v_layout = QVBoxLayout()

        self.label = QLabel(str(self.count), self)
        self.label.setStyleSheet("font-size: 32px;")
        self.v_layout.addWidget(self.label)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.btn_add = QPushButton("加一", self)
        self.btn_add.setFixedHeight(50)
        self.btn_add.clicked.connect(self.increment)
        self.v_layout.addWidget(self.btn_add)

        self.btn_reset = QPushButton("清零", self)
        self.btn_reset.setFixedHeight(50)
        self.btn_reset.clicked.connect(self.reset)
        self.v_layout.addWidget(self.btn_reset)

        self.setLayout(self.v_layout)

        # 添加快捷键Esc退出程序
        QShortcut(QKeySequence("Esc"), self, self.close)

        self.show()

    def increment(self):
        self.count += 1
        self.label.setText(str(self.count))

    def reset(self):
        self.count = 0
        self.label.setText(str(self.count))

    def load_count(self):
        if os.path.exists(COUNT_FILE):
            try:
                with open(COUNT_FILE, "r") as f:
                    return int(f.read())
            except Exception:
                return 0
        return 0

    def save_count(self):
        with open(COUNT_FILE, "w") as f:
            f.write(str(self.count))

    def closeEvent(self, event):
        self.save_count()
        event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = CounterApp()
    sys.exit(app.exec())
